import { TokenDataBase } from "../token"

export interface Meta {
  name: string
  keys: string[]
  MetaDatas: { [key: string]: any }
}

export function getMeta(constructor: any): Meta {
  return constructor.prototype.$REDIS_META || (constructor.prototype.$REDIS_META = {
    name: '',
    // 这里的两个字段是为配合 token 使用
    keys: [
      // 生成时间
      'iat',
      // 超时时间
      'exp'
    ] as (keyof TokenDataBase)[],
    MetaDatas: {
      iat: Number,
      exp: Number
    } as Record<keyof TokenDataBase, any>
  } as Meta)
}

export function Entity(name: any, options: any) {
  let metaName = ''
  if (name && typeof name === 'string') {
    metaName = name
  } else if (!name && options && typeof options.name === 'string') {
    metaName = options.name
  }

  return function(constructor: Function) {
    const meta = getMeta(constructor)

    meta.name = metaName || constructor.name
  }
}

export function Column() {
  return function(target: any, propertyKey: string) {
    const meta = getMeta(target.constructor)
    const reflectMetadataType = Reflect && Reflect.getMetadata ? Reflect.getMetadata("design:type", target, propertyKey) : undefined
    meta.keys.push(propertyKey)
    meta.MetaDatas[propertyKey] = reflectMetadataType
  }
}

export function hansMeta(constructor: any): boolean {
  return !!constructor.prototype.$REDIS_META
}

// 类实例 转 普通对象
export function instance2Object(target: any) {
  if (hansMeta(target.constructor)) {
    const meta = getMeta(target.constructor)
    const result = {}
    meta.keys.forEach(key => {
      result[key] = target[key] || ''
    })
    return result
  }
  return target
}